import { message, Table } from 'antd'
import { SizeType } from 'antd/lib/config-provider/SizeContext'
import React, { useEffect, useState } from 'react'
import { request } from '../../api/request'
import HomeStore from '../../stores/HomeStory'

import '../../config/dark-theme.less'

interface SmallTableProps {
  HomeStore: HomeStore
  Columns?: any[]
  Size?: SizeType
  Key?: string
  refresh?: string
  url?: string
  getParams?: string
}

const SmallTable: React.FC<SmallTableProps> = (props: SmallTableProps) => {
  const {
    getParams = '',
    Columns = [],
    Size = 'small',
    refresh = '',
    url = '',
  } = props

  const [datasource, setDatasource] = useState([] as any)
  const [total, setTotal] = useState(0)
  const [loadding, setLoadding] = useState(false)
  const [pages, setPages] = useState({ pageNum: 1, pageSize: 10 })

  useEffect(() => {
    getData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refresh])

  const getData = (pageNum?: number, pageSize?: number) => {
    let _pageNum = pageNum === undefined ? pages.pageNum : pageNum
    let _pageSize = pageSize === undefined ? pages.pageSize : pageSize

    setLoadding(true)
    request
      .get({
        url:
          url + '&pageNum=' + _pageNum + '&pageSize=' + _pageSize + getParams,
      })
      .then((data: any) => {
        if (data.code === 200) {
          setDatasource(data.results.records)
          setTotal(data.results.total)
        } else {
          message.error('获取数据失败！')
        }
        setLoadding(false)
      })
      .catch(() => {
        message.error('请求失败！')
      })
      .finally(() => {
        setLoadding(false)
      })
  }

  return (
    <Table
      key='id'
      id='table'
      dataSource={datasource}
      columns={Columns}
      size={Size}
      loading={loadding}
      scroll={{ y: 'calc(100vh - 150px - 160px)' }}
      pagination={{
        total: total,
        showQuickJumper: true,
        // hideOnSinglePage: true,
        responsive: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showSizeChanger: true,
        showTotal: (_total: number) => {
          return `总共 ${_total} 条`
        },
        onChange: (page: number, pageSize: number | undefined) => {
          getData(page, pageSize)
          setPages({ pageNum: page, pageSize: pageSize as number })
        },
      }}
    />
  )
}

export default SmallTable
